package com.qiwx.pigeon.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.DateTimeUtils;
import com.qiwx.pigeon.activity.common.MyNumberPicker;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @description
 * @Author qiwx
 * @Date 2020-06-28 17:55
 **/
public class SelectDatePopWindow extends PopupWindow {
    TextView timeTitle;
    MyNumberPicker yearNumberPicker;
    MyNumberPicker monthNumberPicker;
    MyNumberPicker dayNumberPicker;
    TextView txtdayNumberPicker;
    LinearLayout dialLayout;
    TextView txt_cancel;
    TextView txt_ok;
    private Context context;
    private LayoutInflater inflater;
    private View mView;
    private View lin_bootom;


    private int currYear = DateTimeUtils.getCurrent(DateTimeUtils.TimeType.YEAR);//默认当前年
    private int currMonth = DateTimeUtils.getCurrent(DateTimeUtils.TimeType.MONTH);//默认当前月
    private int currDay = DateTimeUtils.getCurrent(DateTimeUtils.TimeType.DAY);//默认当前日

    private int maxYear = DateTimeUtils.getCurrent(DateTimeUtils.TimeType.YEAR);//默认当前年
    private int minYear;
    private int minMonth = 1;

    private int minDay = 1;
    private int term; //新增期限值，从当前日期往后推多少年
    private boolean isShowDay = true;//是否显示到天 默认显示
    private IselectListener iselectListener = null;

    String title;
    int type = 0;


    public SelectDatePopWindow(Context context
    ) {
        this.context = context;
        this.title = title;
        this.maxYear = currYear;
        this.minYear = 1990;
        this.minMonth = 1;
        this.minDay = 1;
        this.term = 0;
        this.isShowDay = true;
        initView();
    }

    public void setTitle(String title) {
        timeTitle.setText(title);
    }

    public void initData(int type, int minYear, int minMonth) {
        this.minYear = minYear;
        this.minMonth = minMonth;
        this.type = type;
        init();
    }

    public void setListener(IselectListener listener) {
        this.iselectListener = listener;
    }

    private void init() {
        yearNumberPicker.setMaxValue(maxYear);
        yearNumberPicker.setMinValue(minYear);
        yearNumberPicker.setValue(currYear);

        if (maxYear < currYear) {
            currYear = maxYear;
            yearNumberPicker.setValue(currYear);
            monthNumberPicker.setMaxValue(12);
            monthNumberPicker.setMinValue(1);
            monthNumberPicker.setValue(1);
        } else {
            monthNumberPicker.setMaxValue(currMonth);
            monthNumberPicker.setMinValue(minMonth);
            monthNumberPicker.setValue(currMonth);
        }


        dayNumberPicker.setMaxValue(currDay);
        dayNumberPicker.setMinValue(1);
        dayNumberPicker.setValue(currDay);


        if (term != 0 && term > 0) {

            minYear = currYear;
            maxYear = currYear + term;

            minMonth = currMonth;

            yearNumberPicker.setMaxValue(currYear + term);
            yearNumberPicker.setMinValue(currYear);
            yearNumberPicker.setValue(currYear + 1);

            monthNumberPicker.setMaxValue(currMonth);
            monthNumberPicker.setMinValue(1);
            monthNumberPicker.setValue(currMonth);

            dayNumberPicker.setMinValue(1);
            dayNumberPicker.setValue(currDay - 1);

            if (is31(currMonth)) {
                dayNumberPicker.setMaxValue(31);
            } else {
                if (currMonth == 2) {
                    if (isRunNian(String.valueOf(currYear))) {
                        dayNumberPicker.setMaxValue(29);
                    } else {
                        dayNumberPicker.setMaxValue(28);
                    }

                } else {
                    dayNumberPicker.setMaxValue(30);
                }
            }

        }
        updateMonth();

    }

    private void initView() {
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mView = inflater.inflate(R.layout.act_day_sheettime, null);
        timeTitle = mView.findViewById(R.id.time_title);
        yearNumberPicker = mView.findViewById(R.id.yearNumberPicker);
        monthNumberPicker = mView.findViewById(R.id.monthNumberPicker);
        dayNumberPicker = mView.findViewById(R.id.dayNumberPicker);
        txtdayNumberPicker = mView.findViewById(R.id.txtdayNumberPicker);
        lin_bootom = mView.findViewById(R.id.lin_bootom);
        txt_cancel = mView.findViewById(R.id.txt_cancel);
        txt_ok = mView.findViewById(R.id.txt_ok);
        txt_cancel.setOnClickListener(v -> {
            cancel(v);
        });
        txt_ok.setOnClickListener(v -> {
            time_done(v);

        });
        // 设置SelectPicPopupWindow的View
        this.setContentView(mView);
        // 设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(WindowManager.LayoutParams.FILL_PARENT);
        // 设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        // 设置SelectPicPopupWindow弹出窗体动画效果
//        this.setAnimationStyle(ResourceUtils.getIdByName(context, "style", "AnimBottom"));
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        // 设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        // mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
        mView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                int height = lin_bootom.getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        dismiss();
                    }
                }
                return true;
            }
        });
        setBackgroundDrawable(context.getResources().getDrawable(android.R.color.transparent));
//        maxYear = intent.getIntExtra("maxYear", currYear);
//        minYear = getIntent().getIntExtra("Minyear", 1990);
//        minMonth = getIntent().getIntExtra("MinMonth", 1);
//        minDay = getIntent().getIntExtra("MinDay", 1);
//        term = getIntent().getIntExtra("term", 0);
//        isShowDay = getIntent().getBooleanExtra("isShowDay", true);
//        //maxMonth = getIntent().getIntExtra("maxMonth", 1);
//        String title = intent.getStringExtra(Constant.KEY_TITLE);
        if (!TextUtils.isEmpty(title)) {
            timeTitle.setText(title);
        }
        if (!isShowDay) {
            dayNumberPicker.setVisibility(View.GONE);
            txtdayNumberPicker.setVisibility(View.GONE);
        }
        yearNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        monthNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        dayNumberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        yearNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                int year = picker.getValue();
                currYear = year;
                updateMonth();
            }
        });
        monthNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                int month = picker.getValue();
                currMonth = month;
                updateMonth();

            }
        });
        dayNumberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                int day = picker.getValue();
                currDay = day;
            }
        });
        init();
    }

    public void updateMonth() {
        //当前年
        if (term != 0 && term > 0) {

            int year = yearNumberPicker.getValue();

            if (year == minYear) {
                monthNumberPicker.setMaxValue(12);
                monthNumberPicker.setMinValue(minMonth);
            } else if (year == maxYear) {
                monthNumberPicker.setMaxValue(minMonth);
                monthNumberPicker.setMinValue(1);
            } else {
                monthNumberPicker.setMaxValue(12);
                monthNumberPicker.setMinValue(1);
            }
        } else {

            if (currYear == DateTimeUtils.getCurrent(DateTimeUtils.TimeType.YEAR)) { //如果选择当前年，则重新设置月和日的范围，不等大于当前月，不能大于当前日
                monthNumberPicker.setMaxValue(DateTimeUtils.getCurrent(DateTimeUtils.TimeType.MONTH));
                monthNumberPicker.setMinValue(1);
                if (currMonth == DateTimeUtils.getCurrent(DateTimeUtils.TimeType.MONTH)) {
                    dayNumberPicker.setMaxValue(DateTimeUtils.getCurrent(DateTimeUtils.TimeType.DAY));
                } else {
                    dayNumberPicker.setMaxValue(31);
                }

            } else if (yearNumberPicker.getValue() == minYear) {
                monthNumberPicker.setMaxValue(12);
                monthNumberPicker.setMinValue(minMonth);
            } else {
                monthNumberPicker.setMaxValue(12);
//            monthNumberPicker.setValue(currMonth);
                monthNumberPicker.setMinValue(1);
            }
        }


        updateDay();

    }

    public void updateDay() {
        int year = yearNumberPicker.getValue();
        int month = monthNumberPicker.getValue();
        if (is31(month)) {
            dayNumberPicker.setMaxValue(31);
        } else {
            if (month == 2) {
                if (isRunNian(String.valueOf(year))) {
                    dayNumberPicker.setMaxValue(29);
                } else {
                    dayNumberPicker.setMaxValue(28);
                }

            } else {
                dayNumberPicker.setMaxValue(30);
            }
        }

        if (term != 0 && term > 0) {

            if (year == minYear && month == minMonth) {
                dayNumberPicker.setMinValue(DateTimeUtils.getCurrent(DateTimeUtils.TimeType.DAY));
            } else if (year == maxYear && month == minMonth) {
                dayNumberPicker.setMaxValue(DateTimeUtils.getCurrent(DateTimeUtils.TimeType.DAY));
                dayNumberPicker.setMinValue(1);
            } else {
                dayNumberPicker.setMinValue(1);
            }

        } else {

            if (year == DateTimeUtils.getCurrent(DateTimeUtils.TimeType.YEAR)) {//如果选择当前年，则重新设置月和日的范围，不等大于当前月，不能大于当前日

                monthNumberPicker.setMaxValue(DateTimeUtils.getCurrent(DateTimeUtils.TimeType.MONTH));
                if (currMonth == DateTimeUtils.getCurrent(DateTimeUtils.TimeType.MONTH)) {
                    dayNumberPicker.setMaxValue(DateTimeUtils.getCurrent(DateTimeUtils.TimeType.DAY));
                }
            } else if (year == minYear && month == minMonth) {//如果选择当前最小年和月日期小于最小日期
                dayNumberPicker.setMinValue(minDay);
            }
        }


    }

    /**
     * 根据月份判断是否是31天
     *
     * @param month
     * @return
     */
    public boolean is31(int month) {
        Pattern pattern = Pattern.compile("([13578]|1[02])");
        Matcher matcher = pattern.matcher(month + "");
        return matcher.matches();
    }

    /**
     * 判断是否是闰年
     *
     * @param year
     * @return
     */
    public boolean isRunNian(String year) {
        Pattern pattern = Pattern.compile("(([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))");
        Matcher matcher = pattern.matcher(year);
        return matcher.matches();
    }

    public void cancel(View view) {
        dismiss();
    }

    public void time_done(View view) {
        back_data();
        dismiss();
    }

    public void back_data() {
        int year = yearNumberPicker.getValue();
        int month = monthNumberPicker.getValue();
        int day = dayNumberPicker.getValue();
        StringBuilder sb = new StringBuilder();
        sb.append(year).append("-");
        if (month < 10) {
            sb.append("0" + month);
        } else {
            sb.append(month);
        }
        sb.append("-");
        if (day < 10) {
            sb.append("0" + day);
        } else {
            sb.append(day);
        }
        if (iselectListener != null) {
            iselectListener.onSelected(type, sb.toString());
        }
    }


    public interface IselectListener {
        void onSelected(int type, String content);
    }


}
